package com.junhong.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Repository;

import com.junhong.dao.UserDao;
import com.junhong.entity.User;

@Repository
public class UserDaoImpl implements UserDao {

	@Resource
	private SessionFactory sessionFactory;

	@Override
	public void add(User user) {
		sessionFactory.getCurrentSession().save(user);
	}

	@Override
	public void update(User user) {
		sessionFactory.getCurrentSession().update(user);
	}

	@Override
	public void delete(User user) {
		sessionFactory.getCurrentSession().delete(user);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> find() {
		return sessionFactory.getCurrentSession().createCriteria(User.class).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> find(Integer pos, Integer rows) {
		return sessionFactory.getCurrentSession().createCriteria(User.class).setFirstResult(pos).setMaxResults(rows)
				.list();
	}

	@Override
	public User getById(Serializable id) {
		return (User) sessionFactory.getCurrentSession().get(User.class, id);
	}

	@Override
	public long count() {
		return (long) sessionFactory.getCurrentSession().createCriteria(User.class)
				.setProjection(Projections.rowCount()).uniqueResult();
	}

	@SuppressWarnings({  "unchecked" })
	@Override
	public List<User> loginUser(User user) {
		String sql = "select userName,password from User where userName=? and password=?";
		Query query = sessionFactory.getCurrentSession().createQuery(sql);
		query.setParameter(0, user.getUserName());
		query.setParameter(1, user.getPassword());
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> existUserWithUserName(String userName) {
		return (List<User>) sessionFactory.getCurrentSession().createQuery("from User where userName='" + userName + "'")
				.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> existUserWithRoleId(Integer roleId) {
		return (List<User>) sessionFactory.getCurrentSession().createQuery("from User where roleid='" + roleId + "'")
				.uniqueResult();
	}

}
